from threading import Event
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler, LoggingEventHandler
import os
import tornado.ioloop
import logging
from logzero import logger
import xlrd
import time
import asyncio
from rethinkdb import r
from .database import db, time_now

class FileHandler(FileSystemEventHandler):
    def __init__(self) -> None:
        self._xrld = None
        self._col_names = None
    def on_created(self, event):
        if os.path.splitext(event.src_path)[1] != '.xls':
            return 
        size = os.path.getsize(event.src_path)
        while size <= 0:
            time.sleep(0.5)
            size = os.path.getsize(event.src_path)
        
        print(size)
        wb = xlrd.open_workbook(event.src_path)
        sheet = wb.sheet_by_index(0)
        #获取该sheet中的有效行数
        nrows = sheet.nrows
        contacts = list()

        #通过列名获取列索引
        self.getColIndex(sheet, ['分类名', '地区市', '手机'])

        for rowx in range(1, nrows):
            phones = None
            phone_value = sheet.cell(rowx, self._col_names['手机']).value
            if ',' in phone_value:
                phones = phone_value.split(',')
            if not phones is None:
                for p in phones:
                    contact = {
                        'city': sheet.cell(rowx, self._col_names['地区市']).value,
                        "createAt": time_now(),
                        'id': p,
                        'industry': sheet.cell(rowx, self._col_names['分类名']).value,
                        'provider': '',
                        'status': 'unused',
                        'test': False,
                        'udid': '',
                        'updateAt': time_now(),
                        'user': ''
                    }
                    contacts.append(contact)
            else:
                contact = {
                        'city': sheet.cell(rowx, self._col_names['地区市']).value,
                        "createAt": time_now(),
                        'id': phone_value,
                        'industry': sheet.cell(rowx, self._col_names['分类名']).value,
                        'provider': '',
                        'status': 'unused',
                        'test': False,
                        'udid': '',
                        'updateAt': time_now(),
                        'user': ''
                    }
                contacts.append(contact)
        i = 0
        for contact in contacts:
            try:
                asyncio.run(db.table("contacts").insert(contact))
                i += 1
                logger.info('联系人 [ %s ] 导入成功. 当前进度 %s', contact['id'], round(i/len(contacts)*100, 0))
            except Exception as e:
                logger.warn("导入出错，错误信息 %s", e)
        
    def getColIndex(self, sheet, col_names: list):
        if not self._col_names is None:
            return

        self._col_names = dict()
        for name in col_names:
            for i in range(sheet.ncols):
                if '分类名' == name == sheet.cell_value(0, i):
                    self._col_names['分类名'] = i
                if '地区市' == name == sheet.cell_value(0, i):
                    self._col_names['地区市'] = i
                if '手机' == name == sheet.cell_value(0, i):
                    self._col_names['手机'] = i

        
    def on_modified(self, event):
        
        print("File is modified ", event.src_path)
    def on_deleted(self, event):
        print("File is deleted ", event.src_path)

class Importor(object):
    def __init__(self) -> None:
        self._observer = Observer()
        self._xlrd = None

    def watch_dir(self, handler: FileHandler, path:str):
        
        self._observer.schedule(event_handler=handler, path=path, recursive=True)
        self._observer.start()


    
